package com.kobe.tokendemo.shiro;

import com.kobe.tokendemo.entity.SysPermission;
import com.kobe.tokendemo.entity.SysRole;
import com.kobe.tokendemo.entity.UserInfo;
import com.kobe.tokendemo.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 创建 JYQ  on  2018/11/2,16:25
 */
@Component
public class SimpleRealm extends AuthorizingRealm {
    @Resource
    private UserInfoService userInfoService;
    @Override
    public String getName() {
        return "simpleRealm";
    }
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof SimpleUsernameToken;
    }

    @Override
//    授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Subject subject = SecurityUtils.getSubject();
//        认证存储得是userInfo
        UserInfo user =(UserInfo)subject.getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        for
        for (SysRole role : user.getRoleList()) {
            info.addRole(role.getRole());
            for (SysPermission permission : role.getPermissions()) {
                info.addStringPermission(permission.getPermission());
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        String password = (String)token.getCredentials();
        UserInfo user = this.userInfoService.login(username, password);
        if (user != null) {
//             从数据库中查到数据
            SimpleAuthenticationInfo authenticationInfo =
//                    为了方便之后的调用,主要信息存用户详情
                    new SimpleAuthenticationInfo(user,password,getName());
            return  authenticationInfo;

        }else {
           throw new AuthenticationException("登录失败");
    }
}
}
